<?php

namespace app\admin\controller\tpextbuilder;

use tpext\builder\common\Builder;
use tpext\builder\common\Module;
use app\common\controller\BackendNew;

/**
 * Undocumented class
 * @title 导入
 */
class Import extends BackendNew
{
    protected $noNeedRight = ['*'];
    
    /**
     * Undocumented function
     *
     * @title 上传文件弹窗
     * @return mixed
     */
    public function page()
    {
        $acceptedExts = input('acceptedExts', '');
        $fileSize = input('fileSize');
        $pageToken = input('pageToken');
        $successUrl = input('successUrl');

        if ($fileSize == '' || empty($pageToken) || empty($successUrl)) {
            $this->error('参数有误');
        }

        $importpagetoken = session('importpagetoken');

        $_pageToken = md5($importpagetoken . $acceptedExts . $fileSize);

        if ($_pageToken != $pageToken) {
            $this->error('验证失败');
        }

        $config = Module::getInstance()->getConfig();

        if ($fileSize == 0 || $fileSize == '' || $fileSize > $config['max_size']) {
            $fileSize = $config['max_size'];
        }

        if ($acceptedExts == '*' || $acceptedExts == '*/*' || empty($acceptedExts)) {

            $acceptedExts = $config['allow_suffix'];
        }

        $acceptedExts = explode(',', $acceptedExts);
        $acceptedExts = '.' . implode(',.', $acceptedExts);

        $successUrl = urldecode($successUrl);

        $token = session('uploadtoken') ? session('uploadtoken') : md5('uploadtoken' . time() . uniqid());

        session('uploadtoken', $token);

        $uploadUrl = url('/admin/tpextbuilder/upload/upfiles', ['type' => 'dropzone', 'token' => $token]);

        $this->assign('admin_copyright', '');

        $builder = Builder::getInstance();
        $builder->content()->fetch();

        $script = <<<EOT
        // 默认使用情况
        $("#dropzone-elm").dropzone({
            url: "{$uploadUrl}",
            method: "post",  // 也可用put
            paramName: "file", // 默认为file
            maxFiles: 1,// 一次性上传的文件数量上限
            maxFilesize: '{$fileSize}', // 文件大小，单位：MB
            acceptedFiles: "{$acceptedExts}", // 上传的类型
            addRemoveLinks: false,
            parallelUploads: 1,// 一次上传的文件数量
            dictDefaultMessage: '拖动文件至此或者点击上传',
            dictMaxFilesExceeded: "您最多只能上传1个文件！",
            dictResponseError: '文件上传失败!',
            dictInvalidFileType: "不允许上传的文件类型",
            dictFallbackMessage: "浏览器不受支持",
            dictFileTooBig: "文件过大上传文件最大支持{$fileSize}MB.",
            dictRemoveLinks: "删除",
            dictCancelUpload: "取消",
            init: function () {
                this.on("addedfile", function (file) {
                    // 上传文件时触发的事件
                });
                this.on("success", function (file, data) {
                    if (data.status == '200') {
                        location.href = '{$successUrl}?fileurl=' + encodeURI(data.picurl);
                    }
                    else {
                        parent.lightyear.notify('上传失败-' + data.info, 'danger');
                    }
                    // 上传成功触发的事件
                });
                this.on("error", function (file, data) {
                    // 上传失败触发的事件
                    parent.lightyear.notify('出现错误-' + data, 'danger');
                });
            }
        });
        Dropzone.autoDiscover = false;
EOT;

        $builder->addScript($script);

        return $builder->render();
    }

    /**
     * Undocumented function
     *
     * @title 上传成功
     * @return mixed
     */
    public function afterSuccess()
    {
        $builder = Builder::getInstance('提示');

        $fileurl = input('fileurl');

        $script = <<<EOT
        <p>文件上传成功，但未做后续处理：{$fileurl}</p>
        <pre>
        //指定你的处理action，如 url('afterSuccess')
        \$table->getToolbar()->btnImport(url('afterSuccess'));

        //请在你的控制器实现导入逻辑
        public function afterSuccess()
        {
            \$fileurl = input('fileurl');
            if (is_file(app()->getRootPath() . 'public' . \$fileurl)) {
                // 导入逻辑...
                return Builder::getInstance()->layer()->closeRefresh(1, '导入成功：' . \$fileurl);
            }

            \$builder = Builder::getInstance('出错了');
            \$builder->content()->display('&lt;p&gt;' . '未能读取文件:' . \$fileurl . '&lt;/p&gt;');
            return \$builder->render();
        }
        </pre>

EOT;
        $builder->content()->display($script);
        return $builder->render();
    }
}
